//
//  AfanUserAccountViewModel.swift
//  weibo
//
//  Created by afan on 16/3/26.
//  Copyright © 2016年 阿范. All rights reserved.
//

import UIKit

class AfanUserAccountViewModel: NSObject {
    
    //单例
    static let sharedInstance: AfanUserAccountViewModel = AfanUserAccountViewModel()
    
    //账号
    var userAccount:AfanUserAccount?
    
    //账户是否登录
    var userLogin: Bool{
        get {
            return userAccount != nil
        }
    }
    
    
    
    private override init() {
        super.init()
        userAccount = loadUserAccount()
    }
    
    

    
    
    
    
    
    ///使用 code 加载 access_token,post请求
    func loadAccessToken(code: String,completion: (error: NSError?) -> ()) {
        // 获取 accessToken 的 url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //拼接参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        
        
        AfanNetworkTool.sharedInstance.requestPOST(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil{
                completion(error: error)
            }
            self.userAccount = AfanUserAccount(dict: result!)
            //保存到沙盒
            self.saveUserAccount()
            //通知控制器
            completion(error: nil)
        }
//        AfanNetworkTool.sharedInstance.afnManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            
//            //请求成功
////            print("result\(result)")
//            
//            //将 accountToken 保存起来
//            if let dict = result as? [String : AnyObject]{
//                //把网络返回的字典转模型,赋值给属性
//                self.userAccount = AfanUserAccount(dict: dict)
//                print("---------------------")
//                print("self.userAccount:\(self.userAccount)")
//                print("---------------------")
//                completion(error: nil)
//                
//                self.saveUserAccount()
//            }
//
//            }) { (_, error) -> Void in
//                print("error\(error)")
//                completion(error: error)
//        }
    }
    
    ///账号保存路径
    private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    
    /// 保存模型到沙盒
    private func saveUserAccount() {
        if userAccount != nil{
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    
    /// 从沙盒中加载
    private func loadUserAccount() ->AfanUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? AfanUserAccount
        
        
        //判断是否为空,和 accountToken 是否过期
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("userAccount: \(userAccount)")
            return userAccount
        }
        
        return nil
    }
    
    ///获取用户信息
    func loadUserInfo(completion:(error: NSError?) -> ()){
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 参数
        let parameters: [String: AnyObject] = [
            "access_token": userAccount!.access_token!,
            "uid": userAccount!.uid!
        ]
        
        
        AfanNetworkTool.sharedInstance.requestGET(urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil{
                completion(error: error)
            }
            self.userAccount?.screen_name = result?["screen_name"] as? String
            self.userAccount?.avatar_large = result?["avatar_large"] as? String
            

            
            // 将账号新的数据保存到沙盒
            self.saveUserAccount()
            
            completion(error: nil)
        }
        
//        AfanNetworkTool.sharedInstance.afnManager.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            
//            let dict = result as? [String : AnyObject]
//            
//            self.userAccount?.screen_name = dict?["screen_name"] as? String
//            self.userAccount?.avatar_large = dict?["avatar_large"] as? String
//            
////            print("xxxxxxxxxx\(self.userAccount?.avatar_large)")
//            
//            
//            self.saveUserAccount()
//            
//            }) { (_, error) -> Void in
//                
//        }
    }
    
    
    
}





















